from decimal import Decimal
from string import Template
from common import handle_mysql
from faker import Faker

import yaml
from jsonpath import jsonpath
from loguru import logger

import json
from os import access
import os
import requests
from posixpath import expanduser
from string import Template
from faker import Faker
from PIL import Image
from common.handle_path import *
import yaml
from common.handle_path import IMG_DIR
from jsonpath import jsonpath
from loguru import logger
from common.handle_redis import HandleRedis

conf = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
conf = os.path.join(conf, 'conf/config.yaml')
conf = yaml.safe_load(open(conf, encoding='utf-8'))
host = conf['test_env']['host']

class Utils:
    @classmethod
    def handle_yaml(cls, file_name):
        """
        读取yaml文件
        :param file_name:
        :return:
        """
        try:
            yaml_data = yaml.safe_load(open(file_name, encoding='utf-8'))
        except Exception as e:
            logger.error(f'yaml文件读取失败，文件名称：{file_name}')
            raise e
        else:
            return yaml_data
    

    @classmethod
    def handle_token(cls, response):
        """
        组装token
        :param response:
        :return:
        """
        # token_type = jsonpath(response.json(), '$..token_type')[0]
        # token_value = jsonpath(response.json(), '$..access_token')[0]
        token_type = jsonpath(response, '$..token_type')[0].capitalize()
        token_value = jsonpath(response, '$..access_token')[0]
        token = f'{token_type} {token_value}'
        return token

    @classmethod
    def handle_template(cls, source_data, replace_data: dict, ):
        """
        替换文本变量
        :param source_data:
        :param replace_data:
        :return:
        """
        res = Template(str(source_data)).safe_substitute(**replace_data)
        return yaml.safe_load(res)

    @classmethod
    def handle_decimal(cls, data: int):
        """
        将小数或整数转换为两位数decimal
        :param data:
        :return:
        """
        x = '{0:.2f}'.format(float(data))
        return Decimal(x)

    @classmethod
    def handle_random_phone(cls):
        """
        生成随机手机号
        :return:
        """
        fake = Faker(locale='zh_CN')
        phone_number = fake.phone_number()
        return phone_number

    @classmethod
    def get_sign(cls):
        """
        获取当前验证码对应的sign
        """
        req_code = requests.get(url= host+ '/mp/admin/validate/code')
        conf_file = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
        conf_file = os.path.join(conf_file, 'conf/config.yaml')
        conf_file = Utils.handle_yaml(file_name=conf_file)
        redis_conf = conf_file['redis']
        db = HandleRedis(**redis_conf)
        all_need_keys = db.keys("*-*-*-*-*")
        if len(all_need_keys) == 0:
            return "暂时没有验证码"
        # all_need_keys中获取最大值
        max_key = {i: db.ttl(i) for i in all_need_keys}
        max_key = max(max_key, key=max_key.get).decode('utf-8')
        value = db.get(max_key)
        return {
            'sign': max_key,
            'code': value
        }

    @classmethod
    def get_Authorization(cls, picCode, picSign, username='admin', password='123456'):
        """
        获取测试环境后台登录接口返回登录态
        """
        url = host + '/mp/admin/login'
        data = {
            'picCode': picCode,
            'picSign': picSign,
            'username': username,
            'password': password
        }
        req = requests.post(url=url, json=data)
        try:
            access_token = req.json()['data']['access_token']
            return 'Bearer ' + access_token
        except KeyError as k:
            print(f'后台login接口调用失败 ===> {req.status_code}')
            return

    @classmethod
    def get_upload_binary(cls, url, headers: dict, file_name: str, type: str):

        """
        获取指定路径文件后，转换2进制文件格式，并请求upload接口，获取返回字段data
        ex: file_name : "1.jpg"
            type : "image/jpeg"
        """
        f_path = os.path.join(IMG_DIR, file_name)
        files = {
            'file': (file_name, open(f_path, 'rb'), type)
        }
        # upload_url = "http://testing.mp.api.union.com/mp/admin/upload"
        req = requests.post(url=url, headers=headers, files=files)
        resp = req.json()
        try:
            if resp['message'] != 'success':
                logger.error(f"upload接口返回错误，{resp}")
                return 
            data = resp['data']
            return data
        except KeyError as k:
            logger.error(f'upload接口返回错误，状态码 : {req.status_code},\n 详情:\n {resp}')
            return

    @classmethod
    def get_toC_Authorization(cls, picCode, picSign, mobile='19521391932', password='ws123456'):
        """
        获取测试环境前台登录接口返回登录态
        """
        url = host + '/mp/auth/login/mobile-pwd'
        data = {
            'picCode': picCode,
            'picSign': picSign,
            'mobile': mobile,
            'password': password
        }
        req = requests.post(url=url, json=data)
        try:
            access_token = req.json()['data']['access_token']
            return 'Bearer ' + access_token
        except KeyError as k:
            print(f'前台login接口调用失败 ===> {req.status_code}')
            return

    @classmethod
    def get_file_size(cls, file):
        """
        获取文件大小
        :param file: 文件名
        :return:
        """
        try:
            f_path = os.path.join(IMG_DIR, file)
            size = os.path.getsize(f_path)
            return size
        except Exception as e:
            return e

    @classmethod
    def join_url(cls, uri:str, params):
        """
        返回需要参数拼接的域名
        """
        index = uri.find('?')
        api = uri[:index] + str(params) + uri[index+1:]
        return api


if __name__ == '__main__':
    # a = Utils.handle_random_phone()
    # print(a)
    # b = Utils.handle_decimal(6)
    # print(b)
    # c = Utils.handle_template('$l',{'k':3,'l':2})
    # print(c)
    # d = Utils.handle_yaml('../conf/config.yaml')
    # print(d)
    # h = Utils.handle_token({"code": 0, "message": "success", "data": {
    #     "access_token": "eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNokjbEKwjAYhN_l5gTa2P6p3QQdHHRQnIzIHxMxUqu0CQjiuxt1O77ju3thTBYt2N1CD4E0-uEYHNpS4D6EX-xT1wn45yNTKqkpiFQtEDj-gVaF-gJO8ZKdGPyYF_cGu-1iYyAMZvPVcm1wyAfXGHJJRXWmhqbSV6RlVbOWVpcTyc5q9kSsToT3BwAA__8.gcDjoy2Pbc3miSThJEvgtXynaflId5z1KYdQ-RhTaxE",
    #     "token_type": "bearer",
    #     "refresh_token": "eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNokjNEKwiAYRt_lv1b43aaz3RtB0cC6F-cmGWvFVAiid8_q7uN8nPOCmAfowI63sACBHKfVhBE6RuC-ht9c8jwTmJ6PQgUTEoWoOIFg0x-0FVZfYHO6FCeFKZai7g_KaLXV6rQz536vjiV_TaFcwtW1t9JRP9aCNhyRDh4lZd61kruNbxDh_QEAAP__.Da3BbMoSEjeHLVvrUiOqofugQEc4Jb1ZttQ7_dEQjOQ",
    #     "expires_in": 1616806625000, "scope": "scope", "jti": "604f6869-e467-45a7-b713-adb7ae66a2c6"}})
    # print(h)
    u = Utils()
    a = u.get_sign()
    x = a['sign']
    y = a['code']
    b = u.get_Authorization(picSign=x, picCode=y)
    aa = u.get_toC_Authorization(picCode=y, picSign=x)

    headers = {'Authorization': aa}
    url = "http://testing.mp.api.union.com/blockbzz/product/imageUpload"
    aaa = u.get_upload_binary(url=url, headers=headers, file_name="blockbzz.apk", type="image/jpeg")
    print(u.host)

    # a=u.get_sign()

    # print(u.get_toC_Authorization(picCode=a['code'], picSign=a['sign']))
    # size = u.get_file_size( "图片.jpeg")

    # print("@" * 80, size)
